package com.example.zyl.inwatchapp;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.file.zip.ZipEntry;
import com.file.zip.ZipFile;
import com.tencent.tws.api.PassThroughDataResultInfo;
import com.tencent.tws.api.PassThroughManager;
import com.tencent.tws.widget.BaseActivity;
import com.tencent.tws.widget.ItemTransformer;
import com.tencent.tws.widget.TWearableListView;
import com.tencent.tws.widget.TwsToast;
import com.tencent.tws.widget.VWearableListView;

import org.ini4j.Wini;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


/*@DES:在测试文件内的效果，采用toast方法给出在哪一步进行具体方法回调。使用者可以根据实际需要打开Toast的注释。
 * 
 * 
 */
public class VerticalListViewActivity extends BaseActivity {
	//there is a listview
    private TWearableListView mWearableListView = null;
    //there is an Adapter,you should override the base method,it do not plays under sample
    private TWearableListView.Adapter mAdapter;
    //there is an Adapter that contains ImageView and text ,it do not plays under sample
    private TWearableListView.Adapter mIconAndText;
    private List<Bitmap> images = new ArrayList<Bitmap>();  //列表图片
    private List<String> items= new ArrayList<String>();   //列表文字
    private List<String> imagePaths= new ArrayList<String>();   //列表图片路径
    private PassThroughManager passThroughManager;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main1);
        passThroughManager = PassThroughManager.getInstance(this);
//        initWatchFace();   //这个不用了，从手机安装到手表
        initView();
        regDataRecver();
	}

    private void regDataRecver()
    {
        passThroughManager.regDataRecver(new PassThroughManager.PassThroughReceiveDataListener()
        {
            @Override
            public void onReceivePassThroughResult(int resultCode, String data)
            {
                if (resultCode == PassThroughDataResultInfo.SUC){
                    try {
                        JSONObject json = new JSONObject(data);
                        if (json.optString("cmd").equals("currentWatchFace")){
                            //获取当前表盘
                            String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
                            File file = new File(sdCard+"/zylWatchFace/config.ini");
                            Wini wini = new Wini(file);
                            json.put("dir",wini.get("config","name"));
                            //返回当前表盘的通知
                            passThroughManager.sendData(json.toString(), "cn.zyl.inwatchappphoneside",null);
                        }else if (json.optString("cmd").equals("changeWatchFace")){
                            //先检查一下目录存不存在，不存在的话就通知手机端传送表盘文件
                            String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
                            File file = new File(sdCard+"/zylWatchFace/"+json.optString("dir"));
//                            PassThroughManager ptm = PassThroughManager.getInstance(VerticalListViewActivity.this);
                            if (file.exists()){
                                //如果目录存在,切换后通知手机切换成功
                                file = new File(sdCard+"/zylWatchFace/config.ini");
                                if (!file.exists())
                                    file.createNewFile();   //这里可能会不存在config.ini
                                Wini wini = new Wini(file);
                                wini.put("config","name",json.optString("dir"));
                                wini.store();
                                json.put("success",true);
                                //这里发送切换表盘的通知吧
                                Intent intent = new Intent();
                                intent.setAction("cn.zyl.watchface.change");  //发送切换表盘的广播
                                VerticalListViewActivity.this.sendBroadcast(intent);
                                passThroughManager.sendData(json.toString(), "cn.zyl.inwatchappphoneside", new PassThroughManager.PassThroughSendDataResultListener() {
                                    @Override
                                    public void onReceiveSendDataResult(int i) {
                                        if (i!= PassThroughDataResultInfo.SUC){
                                            //消息发送失败
                                            Toast.makeText(getApplicationContext(),i+":与“Inwatch助手”通讯失败，请先打开手机端app",Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            }else{
                                //如果目录不存在,就通知手机端传送文件
                                json.put("success",false);
                                passThroughManager.sendData(json.toString(), "cn.zyl.inwatchappphoneside", new PassThroughManager.PassThroughSendDataResultListener() {
                                    @Override
                                    public void onReceiveSendDataResult(int i) {
                                        if (i!= PassThroughDataResultInfo.SUC){
                                            //消息发送失败
                                            Toast.makeText(getApplicationContext(),i+":与“Inwatch助手”通讯失败，请先打开手机端app",Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            }
                        }else if(json.optString("cmd").equals("delWatchFace")){
                            //删除表盘
                            String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
                            if (!json.optString("dir","").equals("")){
                                File file = new File(sdCard+"/zylWatchFace/"+json.optString("dir",""));
                                //删除前重命名一下,不然新建的时候就会报busy的错误
                                File to = new File(file.getAbsolutePath() + System.currentTimeMillis());
                                file.renameTo(to);
                                DeleteFile(to);
                                json.put("success",true);  //删除成功通知
                            }else{
                                json.put("success",false);  //删除失败
                            }
                            //返回当前表盘的通知
                            passThroughManager.sendData(json.toString(), "cn.zyl.inwatchappphoneside",null);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                else
                    Toast.makeText(getBaseContext(), "手表端接收数据失败，错误代码：" + resultCode, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 删除目录
     * @param file
     */
    private void DeleteFile(File file) {
        if (file.exists() == false) {
            return;
        } else {
            if (file.isFile()) {
                file.delete();
                return;
            }
            if (file.isDirectory()) {
                File[] childFile = file.listFiles();
                if (childFile == null || childFile.length == 0) {
                    file.delete();
                    return;
                }
                for (File f : childFile) {
                    DeleteFile(f);
                }
                file.delete();
            }
        }
    }

    /**
     * 复制assets中的表盘资源到sdcard
     */
	private void initWatchFace(){
        try{
            String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
            File file = new File(sdCard+"/zylWatchFace/");
            if (!file.exists()) {
                //给其它安装表盘的话，我考虑再重新写一个吧
                AssetManager assetManager = getAssets();
                String[] files = assetManager.list("");
                for (String file1:files){
                    if (file1.equals("zylWatchFace.zip")){
                        //先从assets复制到sdcard，之后再进行解压吧
                        copyBigDataToSD("zylWatchFace.zip",sdCard+"/zylWatchFace.zip");
                        File dir = new File(sdCard+"/zylWatchFace/");
                        if (!dir.exists())
                            dir.mkdir();
                        File zipfile = new File(sdCard+"/zylWatchFace.zip");
                        unzip(zipfile,sdCard+"/zylWatchFace/");  //解压
                        //mtp的扫描还有问题，算了。
//                        Uri uri = Uri.parse(dir.toString());
//                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri));
//                        MediaScannerConnection.scanFile(this, new String[]{dir.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
//                            @Override
//                            public void onScanCompleted(String path, Uri uri) {
//                                Log.i("zyltest",path);
//                                Log.i("zyltest",uri.getPath());
//                            }
//                        });
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void copyBigDataToSD(String assetsFileName,String strOutFileName) throws IOException
    {
        InputStream myInput;
        OutputStream myOutput = new FileOutputStream(strOutFileName);
        myInput = this.getAssets().open(assetsFileName);
        byte[] buffer = new byte[1024];
        int length = myInput.read(buffer);
        while(length > 0)
        {
            myOutput.write(buffer, 0, length);
            length = myInput.read(buffer);
        }

        myOutput.flush();
        myInput.close();
        myOutput.close();
    }

    /**
     * @param file      待解压文件
     * @param dir       解压后文件的存放目录
     * @throws IOException
     */
    public void unzip(File file, String dir) throws IOException {
        ZipFile zipFile = new ZipFile(file, "GBK");//设置压缩文件的编码方式为GBK
        Enumeration<ZipEntry> entris = zipFile.getEntries();
        ZipEntry zipEntry = null;
        File tmpFile = null;
        BufferedOutputStream bos = null;
        InputStream is = null;
        byte[] buf = new byte[1024];
        int len = 0;
        while (entris.hasMoreElements()) {
            zipEntry = entris.nextElement();
            // 不进行文件夹的处理,些为特殊处理
            tmpFile = new File(dir + zipEntry.getName());
            if (zipEntry.isDirectory()) {//当前文件为目录
                if (!tmpFile.exists()) {
                    tmpFile.mkdir();
                }
            } else {
                if (!tmpFile.exists()) {
                    tmpFile.createNewFile();
                }
                is = zipFile.getInputStream(zipEntry);
                bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
                while ((len = is.read(buf)) > 0) {
                    bos.write(buf, 0, len);
                }
                bos.flush();
                bos.close();
            }
        }
    }

    private void initView() {
        mWearableListView = (TWearableListView)findViewById(R.id.setting_list);
        //读取sdcard的表盘资源
        try{
            String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
            File file = new File(sdCard+"/zylWatchFace");
            if (file.exists()) {
                File[] files = file.listFiles();
                for (File file1:files){
                    if(file1.isDirectory()){  //如果是文件夹
                        File file_config = new File(file1.getAbsolutePath()+"/config.ini");
                        Wini wini = new Wini(file_config);
                        String pic = wini.get("config","Preview");  //读取预览图片
                        if (pic==null||!(new File(file1.getAbsolutePath()+"/"+pic).exists())){
                            imagePaths.add("");  //没有预览图片就使用图标吧
                        }else{
                            imagePaths.add(file1.getAbsolutePath()+"/"+pic);
                        }
                        items.add(file1.getName());
                    }
                }
            }
        }catch(Exception e){
            Toast.makeText(getApplicationContext(),items.size()+":加载表盘出错："+e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }

        mWearableListView.setAdapter(new IconItemAdapter(this,items));
        mWearableListView.setStretchScreenSize(100);
        mWearableListView.setClipChildren(false);
        
        //设置滑动监听器
        mWearableListView.addOnScrollListener(new VWearableListView.OnScrollListener()
        {
            public void onScroll(int scroll)
            {
            	//Toast.makeText(MainActivity.this, "onScroll method call,scroll value is : "+scroll+" !\n", Toast.LENGTH_LONG).show();
            }

            public void onAbsoluteScrollChange(int centralPosition)
            {
            	//Toast.makeText(MainActivity.this, "onAbsoluteScrollChange method call,centralPosition value is : "+centralPosition+" !\n", Toast.LENGTH_LONG).show();
            }

            public void onScrollStateChanged(int scroll)
            {
            	//Toast.makeText(MainActivity.this, "onScrollStateChanged method call,centralPosition value is : "+scroll+" !\n", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCentralPositionChanged(int position)
            {
                //central scale PNG
            	//Toast.makeText(MainActivity.this, "onCentralPositionChanged method call,centralPosition value is : "+scrollState+" !\n", Toast.LENGTH_LONG).show();
            }
        }
        );
        
        //　　设置滑动开始监听，list开始滑动时回调
        mWearableListView.setOnScrollStartedListener(new TWearableListView.onScrollStartedListener()
        {
        	public void onScrollStarted()
        	{
        		//Toast.makeText(MainActivity.this, "onScrollStarted method call, Scroll move start !\n", Toast.LENGTH_LONG).show();
        	}
        }
        );
        
        //　　设置滑动停止监听，list滑动结束时回调
        mWearableListView.setOnScrollStoppedListener(new TWearableListView.OnScrollStoppedListener()
        {
        	public void onScrollStopped()
        	{
        		//Toast.makeText(MainActivity.this, "onScrollStopped method call, Scroll move take end !\n", Toast.LENGTH_LONG).show();
        	}
        }
        );
        
        mWearableListView.setItemTransformer(new ItemTransformer()
        {
        	//动时滑动过程中缩放、透明度变化和位移的变化
            @Override
            public void transformItem(View itemView, float scaleFactor)
            {
                //TextView text = (TextView) itemView;
/*            	LinearLayout text =(LinearLayout)itemView;
                text.setScaleX(0.32f * scaleFactor + 0.68f);
                text.setScaleY(0.32f * scaleFactor + 0.68f);
                text.setTranslationX(10 - 10 * scaleFactor);*///you can open it for test
                //text.setTextColor(Color.argb(255, (int) (95 * scaleFactor + 160), (int) (95 * scaleFactor + 160), (int) (95 * scaleFactor + 160)));
            }
        });
        
        //按压监听
        mWearableListView.setOnStateChangedListener(new TWearableListView.OnStateChangedListener()
        		{
        	 @Override
             public void onPressed(View centerView)
             {
        		 //按压时回调
        		 centerView.setScaleX(0.9f);
        		 centerView.setScaleY(0.9f);
        		 //Toast.makeText(MainActivity.this, "onPressed\n", Toast.LENGTH_LONG).show();
             }

             @Override
             public void onReleased(View centerView)
             {
            	 //按压释放时回调
        		 centerView.setScaleX(1.0f);
        		 centerView.setScaleY(1.0f);
        		 //Toast.makeText(MainActivity.this, "onReleased\n", Toast.LENGTH_LONG).show();
             }

        	}
       );
    }
    //inner class of Adapter
  //short description: you can regard VWearableListView.Adapter as RecycleView.Adapater
    public class IconItemAdapter extends VWearableListView.Adapter{

    	//under this data Adapter example,we choose TextView to wrapper user data.
        List<String> msgItems = new ArrayList<String>();

        public IconItemAdapter(Context context, List<String> items)
        {
            msgItems.addAll(items);
        }

        public String getItem(int position)
        {
            return msgItems.get(position);
        }

        public Bitmap getImage(int position){
            return images.get(position);
        }

        public int getItemCount()
        {
            return this.msgItems.size();
        }

        public void onBindViewHolder(VWearableListView.ViewHolder viewHolder, final int position)
        {
            IconItemView iiv = ((IconItemView) viewHolder.itemView);
            iiv.setText(getItem(position));
//            iiv.getImageView().setImageBitmap(getImage(position));
            if (!imagePaths.get(position).equals("")){
                iiv.getImageView().setImageBitmap(BitmapFactory.decodeFile(imagePaths.get(position)));
            }
            iiv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try{
                        File file = new File(Environment.getExternalStorageDirectory()+"/zylWatchFace/config.ini");
                        Wini wini = new Wini(file);
                        String name = wini.get("config","name");
                        if (name.equals(getItem(position))){
                            //这里的提示先不要吧
//                            Toast.makeText(getApplicationContext(),"表盘已切换到["+getItem(position)+"]", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        wini.put("config","name",getItem(position));
                        wini.store();
                        //这里发送切换表盘的通知吧
                        Intent intent = new Intent();
                        intent.setAction("cn.zyl.watchface.change");  //发送切换表盘的广播
                        VerticalListViewActivity.this.sendBroadcast(intent);
                        Toast.makeText(getApplicationContext(), "表盘已切换到["+getItem(position)+"]", Toast.LENGTH_SHORT).show();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }

        public VWearableListView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position)
        {
        	return new VWearableListView.ViewHolder(new IconItemView(viewGroup.getContext()));
        }

    }
    
    //IconItem
    public class IconItemView  extends LinearLayout implements VWearableListView.OnCenterProximityListener{
    	
        public TextView mAppLabel;
        public ImageView mIcon;
        private Context mContext;
        private float mScale;
        
    	public IconItemView(Context context) {
    		this(context, null, 0);
    		// TODO Auto-generated constructor stub
    		
    	}
    	
    	public IconItemView(Context context, AttributeSet attrs, int defStyle)
    	{
            super(context, attrs, defStyle);

            LayoutInflater.from(context).inflate(R.layout.item_layout, this);
            this.mAppLabel = ((TextView) findViewById(R.id.msg_text));
            this.mIcon = (ImageView)findViewById(R.id.Icon);//do View Inflate
            setClipChildren(false);
            setClipToPadding(false);
    	}
    	
    	
    	public void setText(CharSequence string)
    	{
    		mAppLabel.setText(string);
    	}

    	public ImageView getImageView()
    	{
    		return this.mIcon;
    	}

    	@Deprecated
    	public void setTextView(TextView mOutTextView){
    		mAppLabel = mOutTextView;
    		mAppLabel.setTextColor(Color.RED);
    	}
    	
    	@Deprecated
    	public void setImageView(ImageView mOutImageView){
    		mIcon = mOutImageView;
    	}
    	
    	@Deprecated
    	public View doViewInvalidate()
    	{
    		//not safe,just sample
    		this.addView(mIcon);
    		this.addView(mAppLabel);
        	LinearLayout.LayoutParams params = new android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
        	params.gravity = Gravity.CENTER_VERTICAL;
        	this.setLayoutParams(params);
    		//this.setLayoutParams(new android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));
    		return this;
    	}
    	
    	//refresh the display if this itemView  enter center Position
    	@Override
        public void onCenterPosition(boolean animate)
        {
        	mIcon.setAlpha(1.0f);
        	mIcon.setScaleX(1.5f);
        	mIcon.setScaleY(1.5f);
        	mAppLabel.setAlpha(1.0f);
        	mAppLabel.setScaleX(1.5f);
        	mAppLabel.setScaleY(1.5f);
        }

    	//refresh the display if this itemView  get out of center Position
    	@Override
        public void onNonCenterPosition(boolean animate)
        {
    		mIcon.setAlpha(0.4f);
    		mIcon.setScaleX(1.0f);
    		mIcon.setScaleY(1.0f);
    		mAppLabel.setAlpha(0.4f);
    		mAppLabel.setScaleX(1.0f);
    		mAppLabel.setScaleY(1.0f);
        }

    	@Override
        public void setCenter(boolean isCenter)
    	{
    		
    	}

    	@Override
        public boolean isCenter()
    	{
    		return false;
    	}

    }


}
